package middleware

import (
	"github.com/gin-gonic/gin"
	"github.com/vueadmin/global"
	"github.com/vueadmin/pkg/cache"
	"github.com/vueadmin/utils"
	"github.com/vueadmin/utils/conv"
	e "github.com/vueadmin/utils/exception"
	"github.com/vueadmin/utils/response"
)

func AuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		uri := c.Request.URL.Path
		if conv.IsValueInList(uri, global.CONF.System.GetNotAuthUri()) {
			return
		}
		if global.CONF.Sso {
			if global.CONF.Cache.Driver == "redis" && cache.Redis.HGet("login", c.Request.Header.Get("Authorization")) == "" {
				panic(e.ValidateWithCodeError{Msg: "账号已在其他设备登录", Code: 101})
			}
			if global.CONF.Cache.Driver == "gocache" {
				if _, ok := cache.Gocache.Getx("login").(map[string]string)[c.Request.Header.Get("Authorization")]; !ok {
					panic(e.ValidateWithCodeError{Msg: "账号已在其他设备登录", Code: 101})
				}
			}
		}

		access := conv.StringToSlice(conv.String(utils.GetClaims("Access", c)), ",")
		if conv.Int(utils.GetClaims("RoleId", c)) != 1 && !conv.IsValueInList(uri, access) {
			response.Fail(c, "没有权限访问")
			c.Abort()
			return
		}
		c.Next()
	}
}
